package com.better517na.elasticseach.elasticsearch;



import com.better517na.elasticseach.utils.RestUtil;
import com.better517na.elasticseach.utils.StringUtil;

import java.io.IOException;
import java.util.Map;

public  abstract class AbstractHttpElasticSearchClient implements ElasticSearchClient{

    public String post(Index index, String postBody) {
        return RestUtil.post(buildUrl(index),postBody);
    }

    public String get(Index index, String body) {
        try {
            return RestUtil.get(buildUrl(index),body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public Map<String, String> head(Index index) {
       return RestUtil.head(buildUrlIndex(index));
    }


    public String delete(Index index) {
        return null;
    }


    private String buildUrl(Index index){
        StringBuilder reqUrl = new StringBuilder();
        reqUrl.append(getHost()).append(":").append(getPort());

        if (StringUtil.isNotEmpty(index.getIndex())){
            reqUrl.append("/").append(index.getIndex());
        }

        if (StringUtil.isNotEmpty(index.getType())){
            reqUrl.append("/").append(index.getType());
        }

        if (StringUtil.isNotEmpty(index.getAction())){
            reqUrl.append("/").append(index.getAction());
        }


        return reqUrl.toString();
    }

    private String buildUrlIndex(Index index){
        StringBuilder reqUrl = new StringBuilder();
        reqUrl.append(getHost()).append(":").append(getPort());

        if (StringUtil.isNotEmpty(index.getIndex())){
            reqUrl.append("/").append(index.getIndex());
        }

        return reqUrl.toString();
    }

}
